<?php

namespace app\api\model;

use app\common\enums\StatusEnum;

class Lang extends \app\common\model\Lang
{
    /**
     * 根据名称搜索语种
     * @param $name
     * @return false|\think\db\Query[]
     * @throws \think\Exception\DbException
     */
    public static function search($name)
    {
        $model = static::field('id AS langId, icon, name')
            ->where('name', 'like', '%' . $name . '%')
            ->where(['status' => StatusEnum::ENABLED])
            ->select()
            ->toArray();
        foreach ($model as $key => $value) {
            $model[$key]['icon'] = config('file_prefix') . $value['icon'];
        }
        return $model;
    }

    /**
     * 语种列表
     * @param int $page 第几页
     * @param int $size 每页条数
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function getList($page, $size)
    {
        $offset = ($page - 1) * $size;
        $where = [
            'status' => StatusEnum::ENABLED
        ];
        $model = static::field('id AS langId, name, icon')
            ->where($where)
            ->order(['sort_num' => 'desc', 'create_time' => 'desc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();
        foreach ($model as $key => $value) {
            $model[$key]['icon'] = config('file_prefix') . $value['icon'];
        }
        $count = static::where($where)->count();
        return [
            'list' => $model,
            'count' => $count
        ];
    }

    /**
     * 通过语种id获取一条状态正常的语种记录
     * @param $id
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($id)
    {
        return static::field('id, name, icon')
            ->where(['id' => $id, 'status' => StatusEnum::ENABLED])
            ->find();
    }
}